package com.labofjet.messagesender.service.impl;

import com.labofjet.common.dto.ContextDto;
import com.labofjet.common.dto.PageDto;
import com.labofjet.common.service.impl.BaseServiceImpl;
import com.labofjet.common.util.ConverterUtils;
import com.labofjet.common.util.JSONUtils;
import com.labofjet.common.util.MongoQueryUtils;
import com.labofjet.message.dto.MsgMessageSiteMailDto;
import com.labofjet.messagesender.entity.MsgMessageSiteMailCmp;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 站内信  service类 远程调用入口
 */
@Service
public class SdrMessageSiteMailServiceImpl extends BaseServiceImpl {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 列表查询
     *
     * @param result
     * @return
     */
    public PageDto<MsgMessageSiteMailDto> list(ContextDto result) {
        PageDto<MsgMessageSiteMailDto> page = MongoQueryUtils.getInstance(result, mongoTemplate)
                .and("read").and("id").and("receiverId").paging().find(MsgMessageSiteMailCmp.class, MsgMessageSiteMailDto.class);
        return page;
    }

    /**
     * 加载单条
     *
     * @param result
     * @return
     */
    public MsgMessageSiteMailDto load(ContextDto result) {
        PageDto<MsgMessageSiteMailDto> list = this.list(result);
        if (list.getTotal() > 0) {
            return list.getList().get(0);
        }
        return null;
    }

    /**
     * 统计数量
     *
     * @param result
     * @return
     */
    public Long count(ContextDto result) {
        Query query = MongoQueryUtils.getInstance(result).and("read").and("receiverId").getQuery();
        long count = mongoTemplate.count(query, MsgMessageSiteMailCmp.class);
        return count;
    }

    /**
     * save
     *
     * @param contextDto
     * @return
     */
    public MsgMessageSiteMailDto readUnRead(ContextDto contextDto) {
        MsgMessageSiteMailDto dto = JSONUtils.getRequestData(contextDto, MsgMessageSiteMailDto.class);
        MsgMessageSiteMailCmp cmp = mongoTemplate.findById(dto.getId(), MsgMessageSiteMailCmp.class);
        cmp.setRead(dto.getRead());
        mongoTemplate.save(cmp);
        return ConverterUtils.convertOne(cmp, new MsgMessageSiteMailDto());
    }
}
